﻿CREATE PROCEDURE [acms].[TemplateFile_Put]
	@Id int,
	@TemplateId int,
	@Name varchar(50),
	@Path varchar(255),
	@MasterPagePath varchar(255),
	@Theme varchar(50),
	@IsDefault bit,
	@VersionId timestamp,
	@IdOut int output,
    @VersionIdOut timestamp output
AS

	if @TemplateId <= 0
		set @TemplateId = null
	if(@Id is null or @Id <= 0)
		select @Id = Id From TemplateFile_View where TemplateId = @TemplateId and Name = @Name
		
	if Exists(select null from TemplateFile_View where Id = @Id) begin
		update TemplateFiles
		set TemplateId = @TemplateId
			, Name = @Name
			, Path = @Path
			, MasterPagePath = @MasterPagePath
			, Theme = @Theme
			, IsDefault = @IsDefault
		where Id = @Id 
			and VersionId = @VersionId
			and Deleted = 0
			
		if @@rowcount = 0
			return -100
		else
			set @IdOut = @Id
	end
	else begin
		insert into TemplateFiles
			(TemplateId, Name, Path, MasterPagePath, Theme, IsDefault)
		values
			(@TemplateId, @Name, @Path, @MasterPagePath, @Theme, @IsDefault)
		set @IdOut = @@Identity
	end
	
	if @IsDefault = 1 begin
		Update TemplateFiles
		Set IsDefault = 0
		Where TemplateId = @TemplateId
			and Name <> @Name
	end
	
	select @VersionIdOut = VersionId from TemplateFile_View where Id = @IdOut
	
RETURN 0;